package com.example.zhish.gobang.bean;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.example.zhish.gobang.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhish on 2016/4/22.
 */
public class GobangPanel extends View {

    private int mPanelwidth;
    private float mLineheight;
    private int MAX_LINE = 10;
    private Paint mPaint = new Paint();

    private Bitmap mWhitePiece;
    private Bitmap mBlackPiece;
    private float ratioPieceOfLineHeight = 3 * 1.0f / 4;
    private ArrayList<Point> mBlackAray = new ArrayList<>();
    private ArrayList<Point> mWhiteArray = new ArrayList<>();

    //为true时，表示白棋下
    private boolean mIsBlackOrWhite = true;

    private boolean isGameOver = false;
    private boolean isWhiteWinner;

    private int MAX_COUNT_IN_LINE = 5;

    private Context context;

    private void init() {

        mPaint.setAlpha(10);
        mPaint.setColor(Color.rgb(0x8b, 0x8b, 0x83));
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setStyle(Paint.Style.STROKE);

        mWhitePiece = BitmapFactory.decodeResource(getResources(), R.drawable.stone_w2);
        mBlackPiece = BitmapFactory.decodeResource(getResources(), R.drawable.stone_b1);
    }

    public GobangPanel(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        init();
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = Math.min(widthSize, heightSize);
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            width = heightSize;
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            width = widthSize;
        }

        setMeasuredDimension(width, width);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mPanelwidth = w;
        mLineheight = mPanelwidth * 1.0f / MAX_LINE;

        int piecewidth = (int) (mLineheight * ratioPieceOfLineHeight);
        mWhitePiece = Bitmap.createScaledBitmap(mWhitePiece, piecewidth, piecewidth, false);
        mBlackPiece = Bitmap.createScaledBitmap(mBlackPiece, piecewidth, piecewidth, false);

    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {

        int action = event.getAction();

        if (isGameOver) {
            return false;
        }
        if (action == MotionEvent.ACTION_UP) {

            int x = (int) event.getX();
            int y = (int) event.getY();

            Point point = getValidPoint(x, y);

            //判断棋子是否已经存在
            if (mBlackAray.contains(point) || mWhiteArray.contains(point)) {
                return false;
            }
            if (mIsBlackOrWhite) {
                mWhiteArray.add(point);

            } else {
                mBlackAray.add(point);
            }

            mIsBlackOrWhite = !mIsBlackOrWhite;
            //重新绘制图形
            invalidate();
        }
        return true;
    }

    private Point getValidPoint(int x, int y) {
        return new Point((int) (x / mLineheight), (int) (y / mLineheight));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        drawPieces(canvas);
        checkGameOver();
    }

    private void checkGameOver() {
        boolean whiteWin = checkFiveLine(mWhiteArray);
        boolean blackWin = checkFiveLine(mBlackAray);
        if (whiteWin || blackWin) {
            isWhiteWinner = whiteWin;
            isGameOver = true;
            Toast.makeText(context, isWhiteWinner ? "白棋胜利" : "黑棋胜利", Toast.LENGTH_SHORT).show();
        }


    }

    private boolean checkFiveLine(List<Point> list) {

        for (Point p : list) {
            int x = p.x;
            int y = p.y;


            boolean win = checkHorizontal(x, y, list);
            if (win) return true;
            win = checkVertical(x, y, list);
            if (win) return true;
            win = checkLeftDiagonal(x, y, list);
            if (win) return true;
            win = checkRightDiagonal(x, y, list);
            if (win) return true;
        }

        return false;
    }

    /**
     * 判断x，y的棋子是否横向有相邻的5个棋子
     *
     * @param x
     * @param y
     * @param list
     * @return
     */
    private boolean checkHorizontal(int x, int y, List<Point> list) {

        int count = 1;
        //left
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (list.contains(new Point(x - i, y))) {
                count++;
            } else {
                break;
            }
        }

        if (count >= MAX_COUNT_IN_LINE) {
            return true;
        }

        //right
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (list.contains(new Point(x + i, y))) {
                count++;
            } else {
                break;
            }
        }
        if (count >= MAX_COUNT_IN_LINE) {
            return true;
        }


        return false;

    }

    /**
     * 纵向检测
     *
     * @param x
     * @param y
     * @param list
     * @return
     */
    private boolean checkVertical(int x, int y, List<Point> list) {

        int count = 1;
        //top
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (list.contains(new Point(x, y - i))) {
                count++;
            } else {
                break;
            }
        }

        if (count >= MAX_COUNT_IN_LINE) {
            return true;
        }

        //bottom
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (list.contains(new Point(x, y + i))) {
                count++;
            } else {
                break;
            }
        }
        if (count >= MAX_COUNT_IN_LINE) {
            return true;
        }

        return false;

    }

    /**
     * 查看左斜
     *
     * @param x
     * @param y
     * @param list
     * @return
     */
    private boolean checkLeftDiagonal(int x, int y, List<Point> list) {

        int count = 1;
        //top
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (list.contains(new Point(x - i, y - i))) {
                count++;
            } else {
                break;
            }
        }

        if (count >= MAX_COUNT_IN_LINE) {
            return true;
        }

        //bottom
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (list.contains(new Point(x + i, y + i))) {
                count++;
            } else {
                break;
            }
        }
        if (count >= MAX_COUNT_IN_LINE) {
            return true;
        }

        return false;

    }

    /**
     * 右斜检测
     *
     * @param x
     * @param y
     * @param list
     * @return
     */
    private boolean checkRightDiagonal(int x, int y, List<Point> list) {

        int count = 1;
        //top
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (list.contains(new Point(x + i, y - i))) {
                count++;
            } else {
                break;
            }
        }

        if (count >= MAX_COUNT_IN_LINE) {
            return true;
        }

        //botom
        for (int i = 1; i < MAX_COUNT_IN_LINE; i++) {
            if (list.contains(new Point(x - i, y + i))) {
                count++;
            } else {
                break;
            }
        }
        if (count >= MAX_COUNT_IN_LINE) {
            return true;
        }

        return false;

    }

    private void drawBoard(Canvas canvas) {
        int w = mPanelwidth;
        float lineHeight = mLineheight;
        for (int i = 0; i < MAX_LINE; i++) {
            int startX = (int) (lineHeight / 2);
            int endX = (int) (w - lineHeight / 2);

            int y = (int) ((0.5 + i) * lineHeight);
            canvas.drawLine(startX, y, endX, y, mPaint);
            canvas.drawLine(y, startX, y, endX, mPaint);

        }

    }

    private void drawPieces(Canvas canvas) {


        for (int i = 0; i < mWhiteArray.size(); i++) {
            Point whitePoint = mWhiteArray.get(i);
            canvas.drawBitmap(mWhitePiece, (whitePoint.x + (1 - ratioPieceOfLineHeight) / 2) * mLineheight, (whitePoint.y + (1 - ratioPieceOfLineHeight) / 2) * mLineheight, null);
        }

        for (int i = 0; i < mBlackAray.size(); i++) {
            Point blackPoint = mBlackAray.get(i);
            canvas.drawBitmap(mBlackPiece, (blackPoint.x + (1 - ratioPieceOfLineHeight) / 2) * mLineheight, (blackPoint.y + (1 - ratioPieceOfLineHeight) / 2) * mLineheight, null);
        }

    }

    public void start() {
        mWhiteArray.clear();
        mBlackAray.clear();
        isGameOver = false;
        mIsBlackOrWhite = false;
        invalidate();
    }


    private static final String INSTANCE = "instance";
    private static final String INSTANCE_GAME_OVER = "instance_game_over";
    private static final String INSTANCE_WHITE_ARRAY = "instance_white_array";
    private static final String INSTANCE_BLACK_ARRAY = "instance_black_array";

    @Override
    protected Parcelable onSaveInstanceState() {

        Bundle bundle = new Bundle();
        bundle.putParcelable(INSTANCE, super.onSaveInstanceState());
        bundle.putBoolean(INSTANCE_GAME_OVER, isGameOver);
        bundle.putParcelableArrayList(INSTANCE_WHITE_ARRAY, mWhiteArray);
        bundle.putParcelableArrayList(INSTANCE_BLACK_ARRAY, mBlackAray);

        return bundle;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (state instanceof Bundle) {
            Bundle bundle = (Bundle) state;
            isGameOver = bundle.getBoolean(INSTANCE_GAME_OVER);
            mWhiteArray = bundle.getParcelableArrayList(INSTANCE_WHITE_ARRAY);
            mBlackAray = bundle.getParcelableArrayList(INSTANCE_BLACK_ARRAY);
            super.onRestoreInstanceState(bundle.getParcelable(INSTANCE));
            return;
        }

        super.onRestoreInstanceState(state);
    }
}
